package com.af.system.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @author : zhenyun.su
 * @since : 2019/12/03
 * @comment : 签名&加密工具
 *  提供方法：
 *  1 SHA-256签名，按UTF-8编码，返回字节数组: static byte[] sha256(String unSign)
 *  2 MD5签名，按UTF-8编码，返回字节数组:  static byte[] md5(String unSign)
 *  3 签名，按签名算法，待签名值及UTF-8 编码，返回字节数组
 *  static byte[] sign(String algorithm, String unSign)
 *             throws UnsupportedEncodingException, NoSuchAlgorithmException
 *  4 待签名字符串, 按参数和密钥 getUnSignString(Map<String, Object> params, String Token)
 *
 *  配合：EncodeUtils， HttpUtils工具使用
 */

public class AfSignUtils {
    /**
     * @comment : SHA-256签名，按UTF-8编码，返回字节数组
     */
    public static byte[] sha256(String unSign)
            throws UnsupportedEncodingException, NoSuchAlgorithmException {
        return sign("SHA-256", unSign);
    }

    /**
     * @comment : MD5签名，按UTF-8编码，返回字节数组
     */
    public static byte[] md5(String unSign)
            throws UnsupportedEncodingException, NoSuchAlgorithmException {
        return sign("MD5", unSign);
    }

    /**
     * @comment : 签名，按签名算法，待签名值及UTF-8 编码，返回字节数组
     */
    public static byte[] sign(String algorithm, String unSign)
            throws UnsupportedEncodingException, NoSuchAlgorithmException {
        return sign(algorithm, unSign, "UTF-8");
    }

    /**
     * @comment : 待签名字符串, 按参数和密钥
     */
    public static String getUnSignString(Map<String, Object> params, String Token) {
        StringBuilder sortedParams = new StringBuilder();
        params.entrySet().stream().forEachOrdered(paramEntry ->
                sortedParams
                        .append(paramEntry.getKey())
                        .append(paramEntry.getValue())
        );
        sortedParams.append(Token);
        return sortedParams.toString();
    }

    /**
     * @comment : 获取签名值; 按签名算法，待签名值及编码，返回签名字节数组
     * algorithm: SHA-256, MD5  encode: UTF-8
     */
    private static byte[] sign(String algorithm, String unSign, String encode)
            throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        messageDigest.update(unSign.getBytes(encode));
        return messageDigest.digest();
    }

}
